﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Quartz.Api.Helper;
using Quartz.Api.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.Api.Middlewares
{
    public static class DataBaseMildd
    {
        public static void UseDataBase(this IApplicationBuilder applicationBuilder, IWebHostEnvironment env)
        {
            IServiceProvider services = applicationBuilder.ApplicationServices;

            //获取当前环境的根目录
            var path = env.ContentRootPath;
            //获取sqlite连接字符串
            var dbname = Appsettings.app("DbConnection");

            var Conn = ($"Data Source = {path}\\{dbname}").ReplacePath();


            //初始化建库建表
            //创建库
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.Sqlite,
                ConnectionString = Conn,
                InitKeyType = InitKeyType.Attribute
            });
            db.DbMaintenance.CreateDatabase();
            //创建任务表
            db.MappingTables.Add(typeof(TaskOptions).Name, typeof(TaskOptions).Name);
            db.CodeFirst.InitTables(typeof(TaskOptions));
            //创建记录表
            db.MappingTables.Add(typeof(TaskRecord).Name, typeof(TaskRecord).Name);
            db.CodeFirst.InitTables(typeof(TaskRecord));
            //创建请求表
            db.MappingTables.Add(typeof(AccessLog).Name, typeof(AccessLog).Name);
            db.CodeFirst.InitTables(typeof(AccessLog));
            //创建任务行为表
            db.MappingTables.Add(typeof(ActionLog).Name, typeof(ActionLog).Name);
            db.CodeFirst.InitTables(typeof(ActionLog));
            //创建站点信息记录表
            db.MappingTables.Add(typeof(AppLog).Name, typeof(AppLog).Name);
            db.CodeFirst.InitTables(typeof(AppLog));

        }
    }
}
